package com.demo.interceptor;

import cn.hutool.core.util.StrUtil;
import com.demo.constant.TokenConst;
import com.demo.entity.User;
import com.demo.entity.test.UserBo;
import com.demo.jwt.JwtTokenUtil;
import com.demo.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @author zm
 * @description 拦截器
 */
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("请求方式：----"+request.getMethod()+":----"+"拦截到的token:----"+request.getHeader("token"));
        if ("OPTIONS".equals(request.getMethod())) {
            log.info("OPTIONS");
            return true;
        }
        String token = request.getHeader("token");
        //JwtTokenUtil.verifyToken(token);

        return true;

        //获取session中存储的用户信息  TODO 需要修改成自己的用户类 12-21 还未进行修改
//        HttpSession session = request.getSession();
//        UserBo user = (UserBo) session.getAttribute(TokenConst.SESSION_USER);
//        log.info("sesion中的用户信息是："+user);

//        if(user == null){
//            /**
//             * 1.如果token不存在，则跳转等登录页面
//             * 2.为什么要跟上redirectUrl地址：原因--：请求认证服务器成功之后，需要直接返回用户先前请求的地址【示例：在商品界面，认证成功就直接返回商品界面 、在个人中心，认证成功就直接返回个人中心界面】
//             * 3.为什么重定向request.getContextPath() + "/login
//             *   原因：当前用户不存在，就去请求当前项目的登录接口
//             */
//            log.info("拦截器回调域地址是："+SpringContextUtils.getRequestUrl(request));
//            response.sendRedirect(request.getContextPath() + "/login/login?redirectUrl=" + SpringContextUtils.getRequestUrl(request));
//            //response.sendRedirect("https://www.baidu.com");
//            return false;
//        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}
